//生成菜单
var menuItem = Vue.extend({
    name: 'menu-item',
    props:{item:{}},
    template:[
        '<li>',
        '	<a v-if="item.type === 0" href="javascript:;">',
        '		<i v-if="item.icon != null" :class="item.icon"></i>',
        '		<span>{{item.name}}</span>',
        '		<i class="fa fa-angle-left pull-right"></i>',
        '	</a>',
        '	<ul v-if="item.type === 0" class="treeview-menu">',
        '		<menu-item :item="item" v-for="item in item.list"></menu-item>',
        '	</ul>',

        '	<a v-if="item.type === 1 && item.parentId === 0"  :href="\'#\'+item.url">',
        '		<i v-if="item.icon != null" :class="item.icon"></i>',
        '		<span>{{item.name}}</span>',
        '	</a>',

        '	<a v-if="item.type === 1 && item.parentId != 0" :href="\'#\'+item.url"><i v-if="item.icon != null" :class="item.icon"></i><i v-else class="fa fa-circle-o"></i> {{item.name}}</a>',
        '</li>'
    ].join('')
});

//iframe自适应
$(window).on('resize', function() {
	var $content = $('.content');
	$content.height($(this).height() - 154);
	$content.find('iframe').each(function() {
		$(this).height($content.height());
	});
}).resize();

//注册菜单组件
Vue.component('menuItem',menuItem);

var vm = new Vue({
	el:'#rrapp',
	data:{
		user:{},
		menuList:{},
		main:"main.html",
		password:'',
		newPassword:'',
        navTitle:"控制台",
		title:"",
		showBinding: false,
		bindingQrCode:"",
		pollingToo:"",
		verifyKey:"",
		flag:false,
		msgCount: 0,
		documentTitle: "智客推管理平台", // 保存页面原标题
		step: 0,
		titleTimer: null,// 标题定时器
	},
	methods: {
		clickMeToo: function () {
			this.showBinding = !this.showBinding;

			console.log(this.showBinding);

			if (this.showBinding == false) {
				clearInterval(this.pollingToo); // 结束轮询
				this.pollingToo = null;
			} else {
				this.getDateLoopToo(); // 开始轮询
			}

			this.refreshQrCode();
		},
		refreshQrCode: function () {
			this.bindingQrCode = "bindingQrCode.jpg?t=" + $.now();
		},
		getDateLoopToo: function (timeout = 1000) { // timeout可以写死，也可以动态
			console.log('查询1'); // 执行语句
			this.pollingToo = setInterval(() => {
				this.promiseFunToo();
				console.log('查询2'); // 轮询中，执行语句
			}, timeout)
		},
		promiseFunToo: function () {
			console.log('查询3'); // 执行语句
			var data = "verifyKey=" + $.now();
			$.ajax({
				type: "POST",
				url: "sys/bindingPool",
				data: data,
				dataType: "json",
				success: function (result) {
					console.log(result);
					if (result.code == 0) {//登录成功
						console.log('查询4');

						// location.reload();

						vm.newUser();

						clearInterval(vm.pollingToo); // 结束轮询
						vm.pollingToo = null;

						vm.showBinding=false;
					}
				}
			});
			return false;
		},
		newUser: function(){
			var url = "sys/user/info/" + vm.user.userId;
			$.ajax({
				type: "POST",
				url: url,
				success: function (r) {
					vm.user = r.user;
					console.log(vm.user);
				}
			});
			return false;
		},
		getMenuList: function (event) {
			$.getJSON("sys/menu/nav?_"+$.now(), function(r){
				vm.menuList = r.menuList;
			});
		},
		getUser: function(){
			$.getJSON("sys/user/info?_"+$.now(), function(r){
				vm.user = r.user;
				console.log(vm.user);

			});
		},
		getTitle: function(){
			$.getJSON("sys/user/getTitle", function(r){
				vm.title = r.title;
				document.title=r.title+'管理平台';
			});
		},
		updatePassword: function(){
			layer.open({
				type: 1,
				skin: 'layui-layer-molv',
				title: "修改密码",
				area: ['550px', '270px'],
				shadeClose: false,
				content: jQuery("#passwordLayer"),
				btn: ['修改','取消'],
				btn1: function (index) {
					var data = "password="+vm.password+"&newPassword="+vm.newPassword;
					$.ajax({
						type: "POST",
					    url: "sys/user/password",
					    data: data,
					    dataType: "json",
					    success: function(result){
							if(result.code == 0){
								layer.close(index);
								layer.alert('修改成功', function(index){
									location.reload();
								});
							}else{
								layer.alert(result.msg);
							}
						}
					});
	            }
			});
		},
        donate: function () {
            layer.open({
                type: 2,
                title: false,
                area: ['806px', '467px'],
                closeBtn: 1,
                shadeClose: false,
                content: ['http://cdn.lkt.io/donate.jpg', 'no']
            });
        },
		// 消息铃铛绑定鼠标事件 mouseover mouseout
		msgBind: function () {
			let msgLi = $(".navbar-nav li:first").eq(0);
			$(msgLi).mouseover(function() {
				if (vm.msgCount > 0) {
					$("#msgList").css("display", "block");
				}
			});
			$(msgLi).mouseout(function() {
				$("#msgList").css("display", "none");
			});
		},
		refreshMessage: function () {
			// 获取当前登录用户负责的公众号中 今日待处理订单 数量
			vm.updateMessageDetailCount("sys/borderinfo/prePayCount", "preOrderMessage");

			// 获取当前登录用户负责的公众号中 今日待处理投诉 数量
			vm.updateMessageDetailCount("sys/buserinfo/complainCount", "complainMessage");

			// 获取当前登录用户负责的公众号中 待处理提现 数量
			if (vm.flag) {
				vm.updateMessageDetailCount("sys/buserwithdrawlog/withdrawalCount", "withdrawalMessage");
			}
		},
		// 更新消息列表的详情
		updateMessageDetailCount: function (url, selector) {
			$.ajax({
				type: "POST",
				url: url,
				dataType: "json",
				success: function(result){
					if(result.code == 0){
						let latestCount = result.latestCount;// 本次数量
						let previousCount = $("#" + selector + " span").eq(0).text();// 上一次数量

						$("#" + selector + " span").eq(0).text(latestCount);// 数量
						if (latestCount > previousCount) {
							$("#msg-bell").addClass("animation-joggle");// 消息铃铛添加动画
							$("#" + selector + " p").eq(0).css("color", "#dd4b39");

							// 如果有消息，且不在当前页，则启动标题滚动效果，提醒用户
							/*if (document.visibilityState == 'hidden') {// 状态判断：隐藏（离开当前页面）
								if (vm.titleTimer == null) {
									// 开启定时任务，滚动标题
									vm.titleTimer = setInterval("vm.flashTitle()", 200);
								}
							}*/
						}
						$("#" + selector + " p").eq(0).text(result.latestDetail);// 最新的详情
						vm.msgCount += latestCount;
						vm.updateMsgCount();
					};
				}
			})
		},
		// 更新消息铃铛的数值
		updateMsgCount: function () {
			let labelMsgCount = $(".navbar-nav li:first label:first").eq(0);
			if (vm.msgCount > 0 && vm.msgCount < 100) {
				$(labelMsgCount).text(vm.msgCount);
			} else if (vm.msgCount >= 100) {
				$(labelMsgCount).text("99+");
			} else {
				$(labelMsgCount).text("");
			}
		},
		routToTartget: function (index) {
			// 点击后，动画消失
			$("#msg-bell").removeClass("animation-joggle");
			$("#msgList p").css("color", "#333");
			let path = location.href.substring(0, location.href.indexOf("#"));
			if (index == 0) {
				location.href = path + `#modules/sys/borderprepayinfo.html`;
			} else if (index == 1) {
				location.href = path + `#modules/sys/complain.html`;
			} else if (index == 2) {
				location.href = path + `#modules/sys/buserwithdrawlog.html`;
			}
		},
		/**
		 * 页面标题动态效果：来回切换
		 */
		flashTitle: function () {
			vm.step++
			if (vm.step == 3) { vm.step = 1 }
			if (vm.step == 2) {
				vm.changeFavicon("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/favicon-mr.ico");
				document.title = vm.documentTitle;
			}
			if (vm.step == 1) {
				// vm.changeFavicon("/zkt-admin/statics/favicon.ico");
				vm.changeFavicon("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/favicon.ico");
				document.title = "您有新的消息，请注意查收！";
			}
		},
		changeFavicon: function (src) {
			let link = document.createElement('link');
			let	oldLink = document.getElementById('dynamic-favicon');
			link.id = 'dynamic-favicon';
			link.rel = 'shortcut icon';
			link.href = src;
			if (oldLink) {
				document.head.removeChild(oldLink);
			}
			document.head.appendChild(link);
		}
	},
	created: function(){
		this.getMenuList();
		this.getUser();
		this.getTitle();
	},
	updated: function(){
		//路由
		var router = new Router();
		routerList(router, vm.menuList);
		router.start();
	}
});

function routerList(router, menuList){
	for(var key in menuList){
		var menu = menuList[key];
		if(menu.type == 0){
			routerList(router, menu.list);
		}else if(menu.type == 1){
			router.add('#'+menu.url, function() {
				var url = window.location.hash;

				//替换iframe的url
			    vm.main = url.replace('#', '');

			    //导航菜单展开
			    $(".treeview-menu li").removeClass("active");
			    $("a[href='"+url+"']").parents("li").addClass("active");

			    vm.navTitle = $("a[href='"+url+"']").text();

			});
		}
	}
}

$(function () {
	vm.msgBind();

	$.getJSON("sys/menu/queryUserMenu?menuId=127&_"+$.now(), function(r){
		if (r.code == 0) {
			vm.flag = true;// 表示用户有提现申请的权限
			$("#withdrawalMessage").css("display", "block");
		}
		vm.refreshMessage();
	});

	// 1分钟更新一次
	setInterval(function () {
		vm.msgCount = 0;// 先归零，再统计
		$(".navbar-nav li:first label:first").eq(0).text("");
		vm.refreshMessage();
	}, 60000)
})

// 添加 Tab 切换监听事件
/*document.addEventListener("visibilitychange", function () {
	if (document.visibilityState == 'visible') {// 状态判断：显示（切换到当前页面）
		// 还原图标
		vm.changeFavicon("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/favicon-mr.ico");
		// 还原标题
		document.title = vm.documentTitle;
		if (vm.titleTimer != null) {
			// 清除滚动标题定时器
			clearInterval(vm.titleTimer);
			// 变量初始化
			vm.titleTimer = null;
		}
	} else if (document.visibilityState == "hidden") {// 状态判断：隐藏（离开当前页面）
		// 如果铃铛有消息，启动定时器
		if ($("#msg-bell").hasClass("animation-joggle")) {
			if (vm.titleTimer == null) {
				// 开启定时任务，滚动标题
				vm.titleTimer = setInterval("vm.flashTitle()", 200);
			}
		}
	}
})*/

